import { defineStore } from 'pinia';
import { computed, reactive, ref } from 'vue';
import { storage } from '@/utils/LocalStorage.ts';
import operateTeam from '@/apis/operate-team.ts';
import { boardRole } from '@/utils/Const.ts';

export const useTeamStore = defineStore('team', () => {
  // 查看我所在的团队列表
  const teamList = reactive<Array<any>>([]);
  function setTeamList(list: any[]) {
    teamList.length = 0;
    teamList.push(...list);
  }

  // 当前团队ID
  const currentTeamId = ref(storage.get('teamId') || '');
  // 设置当前团队ID
  function setCurrentTeamId(teamId: string) {
    currentTeamId.value = teamId;
    storage.set('teamId', teamId);
  }
  function removeCurrentTeamId() {
    currentTeamId.value = '';
    storage.remove('teamId');
  }

  // 团队成员列表
  const teamMemberList = reactive<Array<any>>([]);
  // 获取用户头像列表
  const teamMemberAvatarList = computed(() => {
    return teamMemberList.map((item) => {
      return item.avatarUrl;
    });
  });
  // 设置当前团队中的团队成员列表
  function setTeamMemberList(memberList: any[]) {
    teamMemberList.length = 0;
    teamMemberList.push(...memberList);
  }

  // 我在当前团队中的角色
  const myTeamRole = ref(-1);
  function setMyTeamRole(role: number) {
    myTeamRole.value = role;
  }

  // 团队白板文件
  const teamBoardList = reactive<Array<any>>([]);
  // 获取由我创建的白板
  const boardCreateByMe = computed(() => {
    return teamBoardList.filter((item) => {
      return item.myRole === boardRole.Owner;
    });
  });
  // 获取由他人创建的白板
  const boardCreateByOthers = computed(() => {
    return teamBoardList.filter((item) => {
      return item.myRole !== boardRole.Owner;
    });
  });
  // 设置团队白板列表
  function setTeamBoardList(boardList: any[]) {
    teamBoardList.length = 0;
    teamBoardList.push(...boardList);
  }

  // 保存当前团队信息
  const teamName = ref('');
  const teamOwner = ref('');
  function setTeamName(name: string) {
    teamName.value = name;
  }
  function setTeamOwner(owner: string) {
    teamOwner.value = owner;
  }

  // 获取当前团队成员 请求操作
  async function getTeamMemberList() {
    try {
      const res = await operateTeam.getTeamMemberList({
        teamId: currentTeamId.value,
      });
      if (res?.code === 1000) {
        removeCurrentTeamId();
        return;
      }
      setTeamMemberList(res?.data.memberList);
      setMyTeamRole(res?.data.myRole);
      return res;
    } catch (e) {
      console.error(e);
    }
  }

  // 获取团队白板列表 请求操作
  async function getBoardListInTeam(
    isRecycleBin: boolean,
    searchName?: string,
  ) {
    try {
      const params: any = {
        teamId: currentTeamId.value,
        isInRecycleBin: isRecycleBin,
      };
      if (searchName) {
        params.likeName = searchName;
      }
      const res = await operateTeam.getBoardListInTeam(params);
      if (res?.code === 1000) {
        removeCurrentTeamId();
        return;
      }
      setTeamBoardList(res.data);
    } catch (e) {
      console.error(e);
    }
  }

  // 获取我所在的团队列表 请求操作
  async function getTeamList() {
    try {
      const res = await operateTeam.getTeamList();
      setTeamList(res?.data);
    } catch (e) {
      console.error(e);
    }
  }

  // 获取当前团队信息 请求操作
  async function getTeamInfo() {
    try {
      const res = await operateTeam.getTeamInfo({
        teamId: currentTeamId.value,
      });
      setTeamName(res?.data.name);
      setTeamOwner(res?.data.creatorNickname);
      return res?.data;
    } catch (e) {
      console.error(e);
    }
  }

  // 修改团队名称 请求操作
  async function updateTeamName(newTeamName: string) {
    try {
      return await operateTeam.updateTeamName({
        teamId: currentTeamId.value,
        newName: newTeamName,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 判断当前团队能否被解散
  async function checkTeamCanDisband() {
    try {
      return await operateTeam.checkTeamCanDisband();
    } catch (e) {
      console.error(e);
    }
  }

  // 获取团队邀请链接
  async function getTeamInviteUrl() {
    try {
      return await operateTeam.getTeamInviteUrl({
        teamId: currentTeamId.value,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 重置团队邀请链接
  async function resetTeamInviteUrl() {
    try {
      return await operateTeam.resetTeamInviteUrl({
        teamId: currentTeamId.value,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 查看团队邀请详情
  async function getTeamInviteDetails(code: string) {
    try {
      return await operateTeam.getTeamInviteDetails({
        inviteCode: code,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 使用邀请码加入团队
  async function joinTeamByInviteCode(code: string) {
    try {
      return await operateTeam.joinTeamByInviteCode({
        inviteCode: code,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 解散团队
  async function disbandTeam() {
    try {
      const res = await operateTeam.disbandTeam({
        teamId: currentTeamId.value,
      });
      removeCurrentTeamId();
      return res;
    } catch (e) {
      console.error(e);
    }
  }

  // 移交团队（仅团队拥有者操作）
  async function transferTeam(receiverId: string) {
    try {
      return await operateTeam.transferTeam({
        teamId: currentTeamId.value,
        receiverId,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 移除团队成员（仅团队拥有者操作）
  async function removeTeamMember(teamMemberId: string) {
    try {
      return await operateTeam.removeMember({
        teamId: currentTeamId.value,
        teamMemberId,
      });
    } catch (e) {
      console.error(e);
    }
  }

  // 退出团队
  async function quitTeam() {
    try {
      return await operateTeam.quitTeam({
        teamId: currentTeamId.value,
      });
    } catch (e) {
      console.error(e);
    }
  }

  return {
    currentTeamId,
    setCurrentTeamId,
    removeCurrentTeamId,

    teamList,
    setTeamList,

    teamMemberList,
    teamMemberAvatarList,
    setTeamMemberList,

    teamBoardList,
    boardCreateByMe,
    boardCreateByOthers,
    setTeamBoardList,

    myTeamRole,
    setMyTeamRole,
    teamName,
    teamOwner,

    getTeamMemberList,
    getBoardListInTeam,
    getTeamList,
    getTeamInfo,
    updateTeamName,
    checkTeamCanDisband,
    getTeamInviteUrl,
    resetTeamInviteUrl,
    getTeamInviteDetails,
    joinTeamByInviteCode,
    disbandTeam,
    transferTeam,
    removeTeamMember,
    quitTeam,
  };
});
